package com.molyfun.parents.im.chatrow;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.Direct;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.easeui.domain.EaseAvatarOptions;
import com.hyphenate.easeui.model.styles.EaseMessageListItemStyle;
import com.molyfun.parents.R;
import com.molyfun.parents.im.ChatMessageList;
import com.molyfun.parents.im.model.ChatMessageEntity;
import com.molyfun.parents.utils.TimeUtils;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;
import mabeijianxi.camera.util.Log;

public abstract class BaseChatRow extends LinearLayout implements View.OnClickListener {
    protected static final String TAG = BaseChatRow.class.getSimpleName();

    protected LayoutInflater inflater;
    protected Context context;
    protected BaseAdapter adapter;
    protected ChatMessageEntity message;
    protected int position;

    protected TextView timeStampView;
    protected CircleImageView userAvatarView;
    protected View bubbleLayout;
    protected TextView usernickView;

    protected TextView percentageView;
    protected ProgressBar progressBar;
    protected ImageView statusView;
    protected Activity activity;

    protected EMCallBack messageSendCallback;
    protected EMCallBack messageReceiveCallback;

    protected ChatMessageList.MessageListItemListener itemClickListener;
    protected EaseMessageListItemStyle itemStyle;

    public BaseChatRow(Context context, ChatMessageEntity message, int position, BaseAdapter adapter) {
        super(context);
        this.context = context;
        this.activity = (Activity) context;
        this.message = message;
        this.position = position;
        this.adapter = adapter;
        inflater = LayoutInflater.from(context);
        initView();
    }


    private void initView() {
        onInflateView();
        timeStampView = (TextView) findViewById(R.id.timestamp);
        userAvatarView = (CircleImageView) findViewById(R.id.iv_userhead);
        bubbleLayout = findViewById(R.id.bubble);
        usernickView = (TextView) findViewById(R.id.tv_userid);

        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        statusView = (ImageView) findViewById(R.id.msg_status);
        if (statusView != null) {
            statusView.setOnClickListener(this);
            if (message.isUseNative()) {
                statusView.setVisibility(View.VISIBLE);
            } else {
                statusView.setVisibility(View.GONE);
            }
        }

        onFindViewById();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.msg_status:
                if (mMsgResendCallback != null) {
                    mMsgResendCallback.onMessageResendCallback(message);
                }
                break;
        }
    }

    private MsgResendCallback mMsgResendCallback;

    public static interface MsgResendCallback {
        public void onMessageResendCallback(ChatMessageEntity chatMessageEntity);
    }

    public void setMsgResendCallback(MsgResendCallback msgResendCallback) {
        this.mMsgResendCallback = msgResendCallback;
    }

    /**
     * set property according message and postion
     *
     * @param message
     * @param position
     */
    public void setUpView(ChatMessageEntity message, int position,
                          ChatMessageList.MessageListItemListener itemClickListener,
                          EaseMessageListItemStyle itemStyle) {
        this.message = message;
        this.position = position;

        this.itemClickListener = itemClickListener;
        this.itemStyle = itemStyle;
        Log.i("BaseChatRow", itemClickListener.toString());
        setUpBaseView();
        onSetUpView();
        setClickListener();
    }

    private boolean isCloseEnough(long var0, long var2) {
        long var4 = var0 - var2;
        if(var4 < 0L) {
            var4 = -var4;
        }
        return var4 < 300001L;
    }

    private void setUpBaseView() {
        // set nickname, avatar and background of bubble
        TextView timestamp = (TextView) findViewById(R.id.timestamp);
        if (timestamp != null) {
            if (position == 0) {
                timestamp.setText(TimeUtils.transForTime(message.getMsgTime()));//DateUtils.getTimestampString(new Date(message.getMsgTime())));
                timestamp.setVisibility(View.VISIBLE);
            } else {
                // show time stamp if interval with last message is > 30 seconds

                ChatMessageEntity prevMessage = (ChatMessageEntity) adapter.getItem(position - 1);
                if (prevMessage != null && isCloseEnough(message.getMsgTime(), prevMessage.getMsgTime())) {
                    timestamp.setVisibility(View.GONE);
                } else {
                    timestamp.setText(TimeUtils.transForTime(message.getMsgTime()));//DateUtils.getTimestampString(new Date(message.getMsgTime())));
                    timestamp.setVisibility(View.VISIBLE);
                }
            }
        }
        if (userAvatarView != null) {
            //set nickname and avatar
//            if (message.direct() == Direct.SEND) {
//                EaseUserUtils.setUserAvatar(context, EMClient.getInstance().getCurrentUser(), userAvatarView);
//            } else {
//                EaseUserUtils.setUserAvatar(context, message.getFrom(), userAvatarView);
//                EaseUserUtils.setUserNick(message.getFrom(), usernickView);
//            }

            if (!TextUtils.isEmpty(message.getHeadimgurl())) {
                Picasso.with(context)
                        .load(message.getHeadimgurl())
                        .placeholder(R.drawable.ic_header_default)
                        .into(userAvatarView);
            } else {
                userAvatarView.setImageResource(R.drawable.ic_header_default);
            }

        }

        if (itemStyle != null) {
            if (userAvatarView != null) {
                if (itemStyle.isShowAvatar()) {
                    userAvatarView.setVisibility(View.VISIBLE);
                    EaseAvatarOptions avatarOptions = EaseUI.getInstance().getAvatarOptions();
                    if (avatarOptions != null && userAvatarView instanceof CircleImageView) {
                        CircleImageView avatarView = ((CircleImageView) userAvatarView);
                        if (avatarOptions.getAvatarShape() != 0)
//                            avatarView.setShapeType(avatarOptions.getAvatarShape());
                        if (avatarOptions.getAvatarBorderWidth() != 0)
                            avatarView.setBorderWidth(avatarOptions.getAvatarBorderWidth());
                        if (avatarOptions.getAvatarBorderColor() != 0)
                            avatarView.setBorderColor(avatarOptions.getAvatarBorderColor());
//                        if (avatarOptions.getAvatarRadius() != 0)
//                            avatarView.setRadius(avatarOptions.getAvatarRadius());
                    }
                } else {
                    userAvatarView.setVisibility(View.GONE);
                }
            }
            if (usernickView != null) {
                if (itemStyle.isShowUserNick())
                    usernickView.setVisibility(View.VISIBLE);
                else
                    usernickView.setVisibility(View.GONE);
            }
//            if (bubbleLayout != null) {
//                if (message.direct() == Direct.SEND) {
//                    if (itemStyle.getMyBubbleBg() != null) {
//                        bubbleLayout.setBackgroundDrawable(((EaseMessageAdapter) adapter).getMyBubbleBg());
//                    }
//                } else if (message.direct() == Direct.RECEIVE) {
//                    if (itemStyle.getOtherBubbleBg() != null) {
//                        bubbleLayout.setBackgroundDrawable(((EaseMessageAdapter) adapter).getOtherBubbleBg());
//                    }
//                }
//            }
        }

    }

    /**
     * set callback for sending message
     */
    protected void setMessageSendCallback() {
        if (messageSendCallback == null) {
            messageSendCallback = new EMCallBack() {

                @Override
                public void onSuccess() {
                    updateView();
                }

                @Override
                public void onProgress(final int progress, String status) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (percentageView != null)
                                percentageView.setText(progress + "%");

                        }
                    });
                }

                @Override
                public void onError(int code, String error) {
                    updateView(code, error);
                }
            };
        }
//        message.setMessageStatusCallback(messageSendCallback);
    }

    /**
     * set callback for receiving message
     */
    protected void setMessageReceiveCallback() {
        if (messageReceiveCallback == null) {
            messageReceiveCallback = new EMCallBack() {

                @Override
                public void onSuccess() {
                    updateView();
                }

                @Override
                public void onProgress(final int progress, String status) {
                    activity.runOnUiThread(new Runnable() {
                        public void run() {
                            if (percentageView != null) {
                                percentageView.setText(progress + "%");
                            }
                        }
                    });
                }

                @Override
                public void onError(int code, String error) {
                    updateView();
                }
            };
        }
//        message.setMessageStatusCallback(messageReceiveCallback);
    }


    private void setClickListener() {
        if (bubbleLayout != null) {
            bubbleLayout.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        if (!itemClickListener.onBubbleClick(message)) {
                            // if listener return false, we call default handling
                            onBubbleClick();
                        }
                    }
                }
            });

        }

        if (statusView != null) {
            statusView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        itemClickListener.onResendClick(message);
                    }
                }
            });
        }

        if (userAvatarView != null) {
            userAvatarView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
//                    if (itemClickListener != null) {
//                        if (message.direct() == Direct.SEND) {
//                            itemClickListener.onUserAvatarClick(EMClient.getInstance().getCurrentUser());
//                        } else {
//                            itemClickListener.onUserAvatarClick(message.getFrom());
//                        }
//                    }
                }
            });
            userAvatarView.setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    if (itemClickListener != null) {
                        if (message.direct() == Direct.SEND) {
                            itemClickListener.onUserAvatarLongClick(EMClient.getInstance().getCurrentUser());
                        } else {
                            itemClickListener.onUserAvatarLongClick(message.getFrom());
                        }
                        return true;
                    }
                    return false;
                }
            });
        }
    }


    protected void updateView() {
        activity.runOnUiThread(new Runnable() {
            public void run() {
                if (message.status() == EMMessage.Status.FAIL) {
                    Toast.makeText(activity, activity.getString(R.string.send_fail) + activity.getString(R.string.connect_failuer_toast), Toast.LENGTH_SHORT).show();
                }

                onUpdateView();
            }
        });
    }

    protected void updateView(final int errorCode, final String desc) {
        activity.runOnUiThread(new Runnable() {
            public void run() {
                if (errorCode == EMError.MESSAGE_INCLUDE_ILLEGAL_CONTENT) {
                    Toast.makeText(activity, activity.getString(R.string.send_fail) + activity.getString(R.string.error_send_invalid_content), Toast.LENGTH_SHORT).show();
                } else if (errorCode == EMError.GROUP_NOT_JOINED) {
                    Toast.makeText(activity, activity.getString(R.string.send_fail) + activity.getString(R.string.error_send_not_in_the_group), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(activity, activity.getString(R.string.send_fail) + activity.getString(R.string.connect_failuer_toast), Toast.LENGTH_SHORT).show();
                }
                onUpdateView();
            }
        });
    }

    protected abstract void onInflateView();

    /**
     * find view by id
     */
    protected abstract void onFindViewById();

    /**
     * refresh list view when message status change
     */
    protected abstract void onUpdateView();

    /**
     * setup view
     */
    protected abstract void onSetUpView();

    /**
     * on bubble clicked
     */
    protected abstract void onBubbleClick();

}
